import React, { useState, useEffect } from 'react';
import { SearchBar, List, Toast, Tag, Button } from 'antd-mobile';
import { DeleteOutline, SearchOutline } from 'antd-mobile-icons';
import Navbar from '../../compounts/navber/Navbar';

function SearchPage() {
    const [searchValue, setSearchValue] = useState('');
    const [searchHistory, setSearchHistory] = useState([]);
    const [searchResults, setSearchResults] = useState([]);
    const [isSearching, setIsSearching] = useState(false);
    const [showHistory, setShowHistory] = useState(true);
    const [currentPage, setCurrentPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const [isLoadingMore, setIsLoadingMore] = useState(false);
    const [pageSize] = useState(10);

    // 热门搜索关键词
    const hotSearchKeywords = [
        '感冒', '发烧', '咳嗽', '头痛', '胃痛', '失眠', '高血压', '糖尿病', '心脏病', '肺炎'
    ];

    // 加载搜索历史
    useEffect(() => {
        const history = localStorage.getItem('searchHistory');
        if (history) {
            setSearchHistory(JSON.parse(history));
        }
    }, []);

    // 保存搜索历史
    const saveSearchHistory = (keyword) => {
        if (!keyword.trim()) return;

        const newHistory = [keyword, ...searchHistory.filter(item => item !== keyword)].slice(0, 10);
        setSearchHistory(newHistory);
        localStorage.setItem('searchHistory', JSON.stringify(newHistory));
    };

    // 清空搜索历史
    const clearSearchHistory = () => {
        setSearchHistory([]);
        localStorage.removeItem('searchHistory');
        Toast.show({ content: '搜索历史已清空' });
    };

    // 删除单个历史记录
    const deleteHistoryItem = (index) => {
        const newHistory = searchHistory.filter((_, i) => i !== index);
        setSearchHistory(newHistory);
        localStorage.setItem('searchHistory', JSON.stringify(newHistory));
    };

    // 点击历史记录
    const handleHistoryClick = (keyword) => {
        setSearchValue(keyword);
        performSearch(keyword);
    };

    // 点击热门搜索
    const handleHotSearchClick = (keyword) => {
        setSearchValue(keyword);
        performSearch(keyword);
    };

    // 生成模拟搜索结果
    const generateMockResults = (keyword, page = 1) => {
        const results = [];
        const startIndex = (page - 1) * pageSize;

        for (let i = 0; i < pageSize; i++) {
            const id = startIndex + i + 1;
            results.push({
                id,
                title: `${keyword}相关症状${id}`,
                description: `这是关于${keyword}的详细描述，包含症状、治疗方法等信息。`,
                type: ['症状', '疾病', '治疗'][Math.floor(Math.random() * 3)],
                tags: [keyword, '常见病', '内科'],
                image: `https://picsum.photos/60/60?random=${id}`,
                views: Math.floor(Math.random() * 10000),
                likes: Math.floor(Math.random() * 1000)
            });
        }

        return results;
    };

    // 执行搜索
    const performSearch = async (keyword) => {
        if (!keyword.trim()) {
            Toast.show({ content: '请输入搜索关键词' });
            return;
        }

        setIsSearching(true);
        setShowHistory(false);
        setCurrentPage(1);
        setHasMore(true);

        try {
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000));

            const results = generateMockResults(keyword, 1);
            setSearchResults(results);

            if (results.length < pageSize) {
                setHasMore(false);
            }

            saveSearchHistory(keyword);
            Toast.show({ content: `找到 ${results.length} 条相关结果` });
        } catch (error) {
            Toast.show({ content: '搜索失败，请重试' });
        } finally {
            setIsSearching(false);
        }
    };

    // 加载更多结果
    const loadMoreResults = async () => {
        if (isLoadingMore || !hasMore) return;

        setIsLoadingMore(true);
        try {
            await new Promise(resolve => setTimeout(resolve, 800));

            const nextPage = currentPage + 1;
            const newResults = generateMockResults(searchValue, nextPage);

            setSearchResults(prev => [...prev, ...newResults]);
            setCurrentPage(nextPage);

            if (newResults.length < pageSize) {
                setHasMore(false);
            }
        } catch (error) {
            Toast.show({ content: '加载失败，请重试' });
        } finally {
            setIsLoadingMore(false);
        }
    };

    // 处理搜索
    const handleSearch = () => {
        performSearch(searchValue);
    };

    // 处理搜索框变化
    const handleSearchChange = (value) => {
        setSearchValue(value);
        if (!value.trim()) {
            setShowHistory(true);
            setSearchResults([]);
        }
    };

    // 滚动到底部自动加载更多
    useEffect(() => {
        let scrollTimer = null;

        const handleScroll = () => {
            if (scrollTimer) {
                clearTimeout(scrollTimer);
            }

            scrollTimer = setTimeout(() => {
                const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
                const clientHeight = document.documentElement.clientHeight || window.innerHeight;

                if (scrollHeight - scrollTop - clientHeight < 100 && hasMore && !isLoadingMore && searchResults.length > 0) {
                    loadMoreResults();
                }
            }, 100);
        };

        if (!showHistory && searchResults.length > 0) {
            window.addEventListener('scroll', handleScroll);
            return () => {
                window.removeEventListener('scroll', handleScroll);
                if (scrollTimer) {
                    clearTimeout(scrollTimer);
                }
            };
        }
    }, [hasMore, isLoadingMore, searchResults.length, showHistory]);

    return (
        <div style={{ minHeight: '100vh', backgroundColor: '#f5f5f5' }}>
            {/* 添加CSS动画样式 */}
            <style>
                {`
                    @keyframes spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                `}
            </style>

            {/* 导航栏 */}
            <Navbar title="搜索" />

            {/* 搜索栏 */}
            <div style={{
                position: 'fixed',
                top: '45px',
                left: 0,
                right: 0,
                zIndex: 999,
                backgroundColor: '#fff',
                padding: '8px 16px',
                borderBottom: '1px solid #eee'
            }}>
                <SearchBar
                    placeholder="搜索疾病、症状、医生、医院..."
                    value={searchValue}
                    onChange={handleSearchChange}
                    onSearch={handleSearch}
                    style={{
                        '--border-radius': '20px',
                        '--background-color': '#f5f5f5'
                    }}
                />
            </div>

            {/* 内容区域 */}
            <div style={{ padding: '16px', paddingTop: '100px' }}>
                {showHistory ? (
                    // 搜索历史和热门搜索
                    <div>
                        {/* 搜索历史 */}
                        {searchHistory.length > 0 && (
                            <div style={{ marginBottom: '24px' }}>
                                <div style={{
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'center',
                                    marginBottom: '12px'
                                }}>
                                    <div style={{ display: 'flex', alignItems: 'center' }}>
                                        <span style={{ marginRight: '8px' }}>🕒</span>
                                        <span style={{ fontSize: '16px', fontWeight: 'bold' }}>搜索历史</span>
                                    </div>
                                    <Button
                                        size='small'
                                        fill='none'
                                        onClick={clearSearchHistory}
                                        style={{ color: '#999', fontSize: '12px' }}
                                    >
                                        清空
                                    </Button>
                                </div>
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                                    {searchHistory.map((item, index) => (
                                        <div
                                            key={index}
                                            style={{
                                                display: 'flex',
                                                alignItems: 'center',
                                                backgroundColor: '#f0f0f0',
                                                borderRadius: '16px',
                                                padding: '6px 12px',
                                                fontSize: '14px',
                                                cursor: 'pointer'
                                            }}
                                            onClick={() => handleHistoryClick(item)}
                                        >
                                            <span>{item}</span>
                                            <DeleteOutline
                                                style={{
                                                    marginLeft: '8px',
                                                    fontSize: '12px',
                                                    color: '#999'
                                                }}
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    deleteHistoryItem(index);
                                                }}
                                            />
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {/* 热门搜索 */}
                        <div>
                            <div style={{
                                display: 'flex',
                                alignItems: 'center',
                                marginBottom: '12px'
                            }}>
                                <span style={{ marginRight: '8px' }}>🔥</span>
                                <span style={{ fontSize: '16px', fontWeight: 'bold' }}>热门搜索</span>
                            </div>
                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                                {hotSearchKeywords.map((keyword, index) => (
                                    <Tag
                                        key={index}
                                        color='primary'
                                        fill='outline'
                                        style={{ cursor: 'pointer' }}
                                        onClick={() => handleHotSearchClick(keyword)}
                                    >
                                        {keyword}
                                    </Tag>
                                ))}
                            </div>
                        </div>
                    </div>
                ) : (
                    // 搜索结果
                    <div>
                        {isSearching ? (
                            <div style={{
                                display: 'flex',
                                justifyContent: 'center',
                                alignItems: 'center',
                                padding: '40px 0'
                            }}>
                                <div style={{
                                    width: '20px',
                                    height: '20px',
                                    border: '2px solid #f3f3f3',
                                    borderTop: '2px solid #1677ff',
                                    borderRadius: '50%',
                                    animation: 'spin 1s linear infinite'
                                }}></div>
                                <span style={{ marginLeft: '12px', color: '#666' }}>搜索中...</span>
                            </div>
                        ) : searchResults.length > 0 ? (
                            <div>
                                <div style={{
                                    marginBottom: '16px',
                                    fontSize: '14px',
                                    color: '#666'
                                }}>
                                    找到 {searchResults.length} 条结果 (第 {currentPage} 页)
                                </div>

                                <List>
                                    {searchResults.map((item) => (
                                        <List.Item
                                            key={item.id}
                                            style={{
                                                backgroundColor: '#fff',
                                                borderRadius: '8px',
                                                marginBottom: '12px',
                                                padding: '16px'
                                            }}
                                        >
                                            <div style={{ display: 'flex', gap: '12px' }}>
                                                <img
                                                    src={item.image}
                                                    alt={item.title}
                                                    style={{
                                                        width: '60px',
                                                        height: '60px',
                                                        borderRadius: '8px',
                                                        objectFit: 'cover'
                                                    }}
                                                />
                                                <div style={{ flex: 1 }}>
                                                    <div style={{
                                                        fontSize: '16px',
                                                        fontWeight: 'bold',
                                                        marginBottom: '8px',
                                                        lineHeight: '1.4'
                                                    }}>
                                                        {item.title}
                                                    </div>
                                                    <div style={{
                                                        fontSize: '14px',
                                                        color: '#666',
                                                        marginBottom: '8px',
                                                        lineHeight: '1.4'
                                                    }}>
                                                        {item.description}
                                                    </div>
                                                    <div style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
                                                        <Tag color='primary' fill='outline' size='small'>
                                                            {item.type}
                                                        </Tag>
                                                        {item.tags.map((tag, index) => (
                                                            <Tag key={index} fill='outline' size='small'>
                                                                {tag}
                                                            </Tag>
                                                        ))}
                                                    </div>
                                                    <div style={{
                                                        fontSize: '12px',
                                                        color: '#999',
                                                        display: 'flex',
                                                        gap: '16px'
                                                    }}>
                                                        <span>👁️ {item.views}</span>
                                                        <span>❤️ {item.likes}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </List.Item>
                                    ))}
                                </List>

                                {/* 加载更多区域 */}
                                {hasMore && (
                                    <div style={{
                                        display: 'flex',
                                        justifyContent: 'center',
                                        padding: '20px 0'
                                    }}>
                                        <Button
                                            size='small'
                                            fill='outline'
                                            onClick={loadMoreResults}
                                            disabled={isLoadingMore}
                                            style={{ minWidth: '120px' }}
                                        >
                                            {isLoadingMore ? (
                                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                                    <div style={{
                                                        width: '12px',
                                                        height: '12px',
                                                        border: '1px solid #f3f3f3',
                                                        borderTop: '1px solid #1677ff',
                                                        borderRadius: '50%',
                                                        animation: 'spin 1s linear infinite'
                                                    }}></div>
                                                    加载中...
                                                </div>
                                            ) : '加载更多'}
                                        </Button>
                                    </div>
                                )}

                                {!hasMore && searchResults.length > 0 && (
                                    <div style={{
                                        textAlign: 'center',
                                        padding: '20px 0',
                                        color: '#999',
                                        fontSize: '14px'
                                    }}>
                                        已加载全部数据
                                    </div>
                                )}
                            </div>
                        ) : (
                            <div style={{
                                display: 'flex',
                                flexDirection: 'column',
                                justifyContent: 'center',
                                alignItems: 'center',
                                padding: '60px 0'
                            }}>
                                <div style={{
                                    fontSize: '48px',
                                    marginBottom: '16px',
                                    opacity: 0.3
                                }}>
                                    🔍
                                </div>
                                <div style={{
                                    fontSize: '16px',
                                    color: '#666',
                                    marginBottom: '8px'
                                }}>
                                    暂无搜索结果
                                </div>
                                <div style={{
                                    fontSize: '14px',
                                    color: '#999'
                                }}>
                                    试试其他关键词吧
                                </div>
                            </div>
                        )}
                    </div>
                )}
            </div>
        </div>
    );
}

export default SearchPage;
